var form;
var layer;
//页面初始化时加载Layui框架
layui.use(['form', 'layer', 'laydate'], function () {
    form = layui.form();
    layer = layui.layer;
    $.removeTableCookie('SpryMedia_DataTables_userTable_userList.jsp');
    initCompany();
    initRole();
    //新增
    $("#addUser").click(function () {
        saveOrUpdateUser(null);
    });

    //layui的change事件
    form.on('select(changeCompany)', function () {
        var companyId = $("#companyId").val();
        if (companyId != -1 && companyId != "") {
            initGroup(companyId);
        } else {
            $("#groupId").empty();
            $("#groupId").append("<option value=''>请选择部门</option>");
            $("#groupId").append("<option value='-1'>全部</option>");
        }
        form.render();
    });

    // 查询
    $("#search").click(function () {
        $.removeTableCookie('SpryMedia_DataTables_userTable_userList.jsp');
        getDataTable(); //要触发的方法
        return false;
    });

    //回车事件
    $(document).keydown(function (event) {
        var code = event.which;
        if (code == 13) {
            $.removeTableCookie('SpryMedia_DataTables_userTable_userList.jsp');
            getDataTable(); //要触发的方法
            return false;
        }
    });
});

/**
 * 初始化公司
 */
function initCompany() {
    $.ajax({
        url: basePath + "company/getAllCompany.action",
        type: "post",
        dataType: "text",
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            if (jsonData.length > 0) {
                $("#companyId").empty();
                if (jsonData.length == 1) {
                    $("#companyId").append("<option value='" + jsonData[0].id + "'>" + jsonData[0].name + "</option>");
                    $("#companyIdtemp").val(jsonData[0].id)
                    initGroup(jsonData[0].id);
                } else if (jsonData.length > 1) {
                    $("#companyId").append("<option value=''>请选择公司</option>");
                    $("#companyId").append("<option value='-1'>全部</option>");
                    for (var i = 0; i < jsonData.length; i++) {
                        $("#companyId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].name + "</option>");
                    }
                }
            }
            form.render();
            getDataTable();
        }
    });
}
/**
 * 初始化部门
 */
function initGroup(companyId) {
    $.ajax({
        url: basePath + "group/getAllGroup.action?companyId=" + companyId,
        type: "post",
        dataType: "text",
        data: companyId,
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            $("#groupId").empty();
            if (jsonData.length > 0) {
                if (jsonData.length == 1) {
                    $("#groupId").append("<option value='" + jsonData[0].id + "'>" + jsonData[0].groupName + "</option>");
                } else if (jsonData.length > 1) {
                    $("#groupId").append("<option value=''>请选择部门</option>");
                    $("#groupId").append("<option value='-1'>全部</option>");
                    for (var i = 0; i < jsonData.length; i++) {
                        $("#groupId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].groupName + "</option>");
                    }
                }
            } else {
                $("#groupId").append("<option value=''>请选择部门</option>");
                $("#groupId").append("<option value='-1'>全部</option>");
            }
            form.render();
        }
    });
}
/**
 * 初始化角色
 */
function initRole() {
    var paramData = {
        "query": "all"
    }
    $.ajax({
        url: basePath + "role/findAllRole.action",
        type: "post",
        dataType: "text",
        data: paramData,
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            if (jsonData.length > 0) {
                $("#roleId").empty();
                $("#roleId").append("<option value=''>请选择角色</option>");
                $("#roleId").append("<option value='-1'>全部</option>");
                for (var i = 0; i < jsonData.length; i++) {
                    $("#roleId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].roleName + "</option>");
                }
            }
            form.render();
        }
    });
}

/**
 * 获取列表
 */
function getDataTable() {
    $('#userTable').dataTable({
        'bProcessing': true,
        'bServerSide': true,
        'fnServerParams': function (aoData) {
            var userName = $.trim($("#userName").val());
            if (userName == "") {
                userName = null;
            }
            var loginName = $.trim($("#loginName").val());
            if (loginName == "") {
                loginName = null;
            }
            var groupId = $("#groupId").val();
            var roleId = $("#roleId").val();
            aoData.push({
                "name": "user.userName",
                "value": userName
            }, {
                "name": "user.loginName",
                "value": loginName
            }, {
                "name": "user.groupId",
                "value": groupId
            }, {
                "name": "user.roleId",
                "value": roleId
            });
        },
        "sAjaxSource": basePath + "user/getUserList.action", // 获取列表
        "sServerMethod": "POST",
        "sPaginationType": "full_numbers",
        "bPaginate": true, // 翻页功能
        "bStateSave": true, // 状态保存
        "bLengthChange": false, // 改变每页显示数据数量
        "bFilter": false, // 过滤功能
        "bSort": false, // 排序功能
        "bInfo": true, // 页脚信息
        "bAutoWidth": false, // 自动宽度
        "bDestroy": true,
        "iDisplayLength": 15, // 每页显示多少行
        "aoColumns": [{
            "sTitle": '排序',
            "mDataProp": "no"
        }, {
            "sTitle": '用户名',
            "mDataProp": "userName"
        }, {
            "sTitle": '登录名',
            "mDataProp": "loginName"
        }, {
            "sTitle": '手机',
            "mDataProp": "cellphone"
        }, {
            "sTitle": '性别',
            "mDataProp": "sexStr"
        }, {
            "sTitle": '年龄',
            "mDataProp": "age"
        }, {
            "sTitle": '邮箱',
            "mDataProp": "email"
        }, {
            "sTitle": '部门',
            "mDataProp": "groupName"
        }, {
            "sTitle": '角色',
            "mDataProp": "roleName"
        }, {
            "sTitle": '创建人',
            "mDataProp": "createUser"
        }, {
            "sTitle": '创建日期',
            "mDataProp": "createTime"
        }, {
            "sTitle": '操作',
            "mDataProp": null
        }],
        "oLanguage": {
            "sUrl": basePath + "plugins/datatable/cn.txt" // 中文包
        },
        "fnDrawCallback": function (oSettings) {
            $('#userTable tbody  tr td').each(function () {
                this.setAttribute('title', $(this).text());
            });
        },
        "fnInitComplete": function () {
        },
        "aoColumnDefs": [{
            "aTargets": [2],
            "fnRender": function (oObj) {
                var userId = oObj.aData.id;
                var loginName = oObj.aData.loginName;
                return '<a href="javascript:void(0);" onclick=detailUser("' + userId + '")>' + loginName + '</a>';
            }
        }, {
            "aTargets": [11],
            "fnRender": function (oObj) {
                var userId = oObj.aData.id;
                var loginUserId = oObj.aData.loginUserId;//登陆用户ID
                var roleType = oObj.aData.roleType;
                if (roleType != 0 && userId != loginUserId) {
                    return "<a data-method=\"repaire\" class=\"layui-btn layui-btn-small layui-btn-normal layui-btn-radius\" onclick=saveOrUpdateUser(\"" + userId + '")>修改</a>'
                        + "<a data-method=\"del\" class=\"layui-btn layui-btn-small layui-btn-danger layui-btn-radius\" onclick=deleteUser(\"" + userId + '")>删除</a>';
                } else {
                    return '<a class="layui-btn layui-btn-small layui-btn-radius layui-btn-disabled">修改</a>'
                        + '<a class="layui-btn layui-btn-small layui-btn-radius layui-btn-disabled">删除</a>';
                }
            }
        }]
    });
}
/**
 * 新增/修改
 */
function saveOrUpdateUser(userId) {
    var url;
    var titleVal;
    var areaVal;
    if (null == userId) {
        url = "jsp/user/addOrUpdateUser.jsp";
        titleVal = "新增用户信息";
        areaVal = ["50%", "64%"];
    } else {
        url = "user/toUpdateOrDetail.action?type=update&id=" + userId;
        titleVal = "修改用户信息";
        areaVal = ["50%", "58%"];
    }
    layer.open({
        type: 2,
        title: titleVal,
        area: areaVal,
        shade: 0.3,
        maxmin: true,
        content: basePath + url,
        zIndex: layer.zIndex,
        success: function (layero) {//弹出后回调
            layer.setTop(layero); //弹窗置于最上层
        }
    });
}

/**
 * 查看详情页面
 */
function detailUser(userId) {
    var url = "user/toUpdateOrDetail.action?type=detail&id=" + userId;
    layer.open({
        type: 2,
        title: '查看用户信息',
        area: ["50%", "60%"],
        shade: 0.3,
        maxmin: true,
        content: basePath + url,
        btn: ['关闭'],
        yes: function (index) {
            layer.close(index); //如果设定了yes回调，需进行手工关闭
        },
        zIndex: layer.zIndex,
        success: function (layero) {
            layer.setTop(layero); //弹窗置于最上层
        }
    });
}

/**
 * 删除
 */
function deleteUser(userId) {
    layer.confirm('确定删除此条数据?', {
        title: " 确认",
        icon: 3,
        skin: 'layui-layer-molv',
        btn: ["确定", "取消"],
        yes: function (index) {
            $.ajax({
                url: basePath + "user/deleteUser.action?id=" + userId,
                type: "post",
                dataType: 'text',
                success: function (data) {
                    if (data != null && data != "" && data == 0) {
                        getDataTable();
                    } else if (data == 1) {
                        layer.open({
                            title: '提示',
                            icon: 0,
                            content: '该人员是区域负责人，请先删除区域！'
                        });
                        getDataTable();
                    } else if (data == 2) {
                        layer.open({
                            title: '提示',
                            icon: 0,
                            content: '无法删除自己的人员信息！'
                        });
                        getDataTable();
                    } else {
                        layer.open({
                            title: '错误',
                            icon: 2,
                            content: '删除失败！'
                        });
                        getDataTable();
                    }
                }
            });
            layer.close(index);
        }
    });
}